package com.gitee.qdbp.jdbc.stream;

import java.util.Map;
import com.gitee.qdbp.able.exception.ServiceException;
import com.gitee.qdbp.able.jdbc.condition.DbWhere;
import com.gitee.qdbp.jdbc.api.CrudDao;

/**
 * 实体+Where后续操作, 只有update!
 *
 * @author zhaohuihua
 * @version 20210529
 */
public class CrudOnEntityWhereByStream<T> {

    protected final CrudDao<T> dao;
    protected final DbWhere where;
    private final T entityObject;
    private final Map<String, Object> entityMap;

    CrudOnEntityWhereByStream(CrudDao<T> dao, T entityObject, DbWhere where) {
        this.dao = dao;
        this.entityObject = entityObject;
        this.entityMap = null;
        this.where = where;
    }

    CrudOnEntityWhereByStream(CrudDao<T> dao, Map<String, Object> entityMap, DbWhere where) {
        this.dao = dao;
        this.entityMap = entityMap;
        this.entityObject = null;
        this.where = where;
    }

    /**
     * 根据条件更新实体对象<br>
     * <pre>
    int rows = qdbcBoot.crudStream(SysUser.class)
        .entity(user)
        // .whereEquals("userId", "U0000001");
        .where("userId").equals("U0000001")
            .and("userState").in(UserState.NORMAL, UserState.LOCKED)
            .end()
        .update();
     * </pre>
     * 
     * @return 受影响行数
     * @throws ServiceException 操作失败
     */
    public int update() throws ServiceException {
        if (entityObject != null) {
            return dao.update(entityObject, where);
        } else if (entityMap != null) {
            entityMap.put("where", where);
            return dao.update(entityMap);
        } else {
            return 0;
        }
    }

    /**
     * 根据条件更新实体对象<br>
     * <pre>
    int rows = qdbcBoot.crudStream(SysUser.class)
        .entity(user)
        // .whereEquals("userId", "U0000001");
        .where("userId").equals("U0000001")
            .and("userState").in(UserState.NORMAL, UserState.LOCKED)
            .end()
        .update(true, true); // 自动填充更新参数, 受影响行数为0时抛异常
     * </pre>
     * 
     * @param fillUpdateParams 是否自动填充更新参数(修改人/修改时间等)
     * @param errorOnUnaffected 受影响行数为0时是否抛异常
     * @return 受影响行数
     * @throws ServiceException 操作失败
     */
    public int update(boolean fillUpdateParams, boolean errorOnUnaffected) throws ServiceException {
        if (entityObject != null) {
            return dao.update(entityObject, where, fillUpdateParams, errorOnUnaffected);
        } else if (entityMap != null) {
            entityMap.put("where", where);
            return dao.update(entityMap, fillUpdateParams, errorOnUnaffected);
        } else {
            return 0;
        }
    }
}
